<?php

namespace app\admin\model\facrm\qywx;


use app\admin\model\Admin;
use fast\Random;
use think\Db;
use think\Exception;
use think\Model;

class User extends Model
{


    // 表名
    protected $name = 'facrm_qywx_user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    /**
     * 获取本地得信息员工信息
     * @param $userid 唯一凭证
     * @param array $wx_confing 企业微信配置
     * @param array $user 微信员工返回的信息 【如果传了，没有此用户会自动添加和更新】
     * @param array $extend 扩展字段
     * @return User|array|bool|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function getUser($userid,$wx_confing=array(),$user=array(), $extend = array())
    {
        $adminModel = new Admin();
        $qywxUserModel = new  self();

        $qywxUser = $qywxUserModel->where('userid', $userid)->find();
        if (!$qywxUser&&!$user) return false;

        Db::startTrans();
        try {
            if (!$qywxUser) {
                //判断admin上是否有对应的帐号是否存在
                if (!$admin = $adminModel->where('username', $userid)->find()) {
                    //不存在就生成默认的帐号
                    $params['username'] = $userid;
                    $params['nickname'] = $user['name'];
                    $params['password'] = isset($user['mobile']) ? $user['mobile'] : Random::alnum();//密码为默认手机，没有手机号就自动生成，
                    $params['salt'] = Random::alnum();
                    $params['email'] = isset($user['email'])?$user['email']:'';
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['avatar'] = isset($user['avatar'])? $user['avatar'] : '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $admin = $adminModel->validate('Admin.add')->create($params);
                    //添加组
                    $dataset = ['uid' => $admin->id, 'group_id' => $wx_confing['group_id']];
                    model('\app\admin\model\AuthGroupAccess')->save($dataset);

                }
                $user['admin_id'] = $admin->id;
                $user['corp_id'] = $wx_confing['corp_id'];
                //不存在插入数据，并且在admin上也插入帐号

                $qywxUser = $qywxUserModel->allowField(true)->create($user, true);
            } else  {
                //更新
                $qywxUser->isUpdate(true)->allowField(true)->update($user, ['userid' => $userid], true);
            }
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::write($e->getMessage());
            Db::rollback();
            return false;

        }
        return $qywxUser;

    }


    /**
     * 拥有者
     */
    public function admin()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'admin_id');
    }
}